<template>
    <van-form scroll-to-error>
        <van-cell-group inset>
            <van-field label="工单编号" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ workNumber }}
                    </div>
                </template>
            </van-field>

            <van-field label="当前状态" readonly label-width="120px">
                <template #input>
                    <div style="color: #bf1920">
                        {{ statusType[currentState] }}
                    </div>
                </template>
            </van-field>

            <div class="work-detail-content-button">
                <van-field v-model="currentPerson.name" label="当前处理人" readonly label-width="120px" />
            </div>


            <van-field label="工单创建人" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ userInfo?.create_by?.name }}
                    </div>
                </template>
            </van-field>

            <van-field label="负责人" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ userInfo?.supervisor?.name }}
                    </div>
                </template>

            </van-field>

            <van-field label="FAB" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ userInfo?.customer?.name }}
                    </div>
                </template>

            </van-field>

            <van-field label="客户联系人" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ userInfo?.reporter?.name }}
                    </div>
                </template>
            </van-field>

            <van-field label="电话" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ userInfo?.reporter_phone }}
                    </div>
                </template>
            </van-field>

            <van-field label="邮箱" readonly label-width="120px">
                <template #input>
                    <div style="width: 165px;" v-if="userInfo?.reporter_email">
                        <van-text-ellipsis :content="userInfo?.reporter_email" expand-text="展开" collapse-text="收起" />
                    </div>
                </template>
            </van-field>

            <van-field label="工单类型" readonly label-width="120px">

                <template #input>
                    <div>
                        {{ ticketInfo.ticket_type ? '咨询&要求' : '问题' }}
                    </div>
                </template>
            </van-field>

            <van-field label="工单分类" readonly label-width="120px">
                <template #input>
                    <div>
                        {{ workType[ticketInfo.ticket_cate] }}
                    </div>
                </template>
            </van-field>

            <van-field label="客户设备编号" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo?.device_sn_cust?.name }}
                    </div>
                </template>
            </van-field>

            <van-field label="设备状态" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo.device_status ? '设备无法运行' : '设备可以运行' }}
                    </div>
                </template>
            </van-field>

            <van-field label="设备型号" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo?.device_type }}
                    </div>
                </template>
            </van-field>

            <van-field label="设备序列号" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo?.device_sn }}
                    </div>
                </template>
            </van-field>

            <van-field label="设备保修到期日" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo?.device_warranty?.substring(0, 10) }}
                    </div>
                </template>
            </van-field>

            <van-field label="部件保修到期日" readonly label-width="120px" v-if="!ticketInfo.ticket_type">
                <template #input>
                    <div>
                        {{ ticketInfo?.component_warranty?.substring(0, 10) }}
                    </div>
                </template>
            </van-field>

            <van-field label="标题" readonly label-width="120px">
                <template #input>
                    <div style="width: 165px;" v-if="ticket.ticket_title">
                        <van-text-ellipsis :content="ticket.ticket_title" expand-text="展开" collapse-text="收起" />
                    </div>
                </template>
            </van-field>

            <van-field label="详细描述" readonly label-width="120px">
                <template #input>
                    <div style="width: 165px;" v-if="ticket.ticket_desc">
                        <van-text-ellipsis :content="ticket.ticket_desc" expand-text="展开" collapse-text="收起" />
                    </div>
                </template>
            </van-field>

            <van-field label="附件" readonly label-width="120px">
                <template #input>
                    <div class="person-name">
                        <div v-for="item in ticket.attachments" :key="item?.file_path" class="file-upload">
                            <span @click="downloadFile(item?.file_name, item?.file_path)">
                                <u> {{ item?.file_name }}</u>
                            </span>
                        </div>
                    </div>
                </template>
            </van-field>

        </van-cell-group>
    </van-form>

    <!-- button -->
    <ButtonActionSheet v-model="buttonShow" :button-list="buttonList" :current-state="currentState"
        :message-show="messageShow" :ticket-info="ticketInfo" :sub-mit-data="subMitData" :fab-id="fabId"
        @btnSuccess="edit" v-if="buttonType === '1'" />

    <!-- 详情列表 -->
    <DetailList :list-data="listData" v-if="buttonType === '1'" />

    <div class="button-container" ref="buttonContainer">
        <van-button block type="primary" color="#bf1920" class="work-detail-dispose" @click="buttonShow = true"
            v-show="buttonType === '1' && (buttonList.length || messageEnum.includes(currentState) && messageShow)">
            处理
        </van-button>
    </div>
</template>

<script setup lang='ts'>
import { useRoute } from 'vue-router';
import { download } from '@/utils/downloadUrl';
import ButtonActionSheet from './ButtonActionSheet.vue'
import { useUserStore } from '@/stores/user'
import DetailList from './DetailList.vue'
import { workType } from '@/enum/clientType'
import { workAttachmentDownload, workEditEcho } from '@/api/worksheets';
import { ButtonType, ListType, StepType, SubMitType, TicketInfoType, TicketType, UserInfoObjType } from '@/api/worksheets/type';
import { nextTick } from 'vue';
import { isEdgeBrowser } from '@/utils/browser';
import { onBeforeUnmount, watch } from 'vue';

defineProps<{
    buttonType: string //是否展示处理按钮
}>()

const emit = defineEmits<{
    (e: 'edit', value: number): void
}>()

const store = useUserStore()

const route = useRoute()

const currentState = ref<number>();

const ticketNumber = ref('')

//工单编号
const workNumber = ref(null)

const messageShow = ref(false)

const buttonShow = ref(false)

const fabId = ref<number>()

const messageEnum = [1, 2, 3, 4]

const step = ref<StepType[]>([])

// 列表
const listData = ref<ListType[]>([])

const buttonList = ref<ButtonType[]>([])

const userInfo = ref<UserInfoObjType>({} as UserInfoObjType)

const ticketInfo = ref<TicketInfoType>({} as TicketInfoType)

const ticket = ref<TicketType>({} as TicketType)

const subMitData = ref<SubMitType>({} as SubMitType)

// 添加buttonContainer ref
const buttonContainer = ref<HTMLElement | null>(null)

//当前处理人
const currentPerson = reactive({
    user_type: null,
    name: ''
})

const workTypeIssue = {
    0: '问题',
    1: '咨询&要求',
}

const statusType = {
    0: '创建工单',
    1: '等待分配',
    2: '处理中',
    3: '对策审批中',
    4: '客户确认中',
    5: '关闭',
}

const workClassify = {
    0: '故障维修',
    1: '精度',
    2: '产品咨询',
    3: '视频',
    4: '资料',
    5: '部件',
}

// 检测是否为安卓设备上的Edge浏览器
const isAndroidEdge = () => {
    const { isEdge, isAndroid } = isEdgeBrowser()
    return isEdge && isAndroid
}

// 设置视口高度变量 - 优化性能，避免不必要的DOM操作
const setViewportHeight = () => {
    const vh = window.innerHeight * 0.01
    document.documentElement.style.setProperty('--vh', `${vh}px`)
    
    // 直接使用固定值，避免DOM计算延迟
    const bottomHeight = isAndroidEdge() ? 160 : 45;
    document.documentElement.style.setProperty('--bottom-height', `${bottomHeight}px`)
}

// 清理视口高度设置
const clearViewportHeight = () => {
    document.documentElement.style.removeProperty('--vh');
    document.documentElement.style.removeProperty('--bottom-height');
}

onMounted(() => {
    // 立即执行一次edit，确保数据尽快加载
    edit()
    // 设置视口高度
    setViewportHeight();
    // 监听窗口大小变化
    window.addEventListener('resize', setViewportHeight);
})

// 在组件卸载前清理
onBeforeUnmount(() => {
    // 移除事件监听器
    window.removeEventListener('resize', setViewportHeight);
    // 清理视口高度设置
    clearViewportHeight();
})

// 监听路由变化
watch(() => route.query.id, (newId, oldId) => {
    if (newId !== oldId) {
        // 路由变化时重新执行
        nextTick(() => {
            setViewportHeight();
        });
    }
}, { immediate: true })

//详情回显
const edit = async () => {
    ticketNumber.value = route.query.id as string
    listData.value = []
    
    // 立即设置按钮状态，不等待API响应
    setViewportHeight();
    
    // 立即设置按钮可见性，避免延迟
    nextTick(() => {
        // 强制重新计算布局
        if (buttonContainer.value) {
            buttonContainer.value.style.display = 'flex';
        }
    });

    try {
        const res: any = await workEditEcho({ ticket_number: route.query.id as string })

        workNumber.value = res.data.ticket_number || ''
        Object.assign(currentPerson, res.data.current_owner)
        step.value = res.data.all_states || []
        buttonList.value = res.data.operations || []
        userInfo.value = res.data?.user_info
        ticketInfo.value = res.data?.ticket_info
        ticket.value = res.data?.ticket
        currentState.value = res.data?.current_state
        fabId.value = userInfo?.value.customer.id
        listData.value = res.data.history || []

        // 查询列表数据不为留言的第一条
        const messageFirst = listData.value.find((item: ListType) => item.type === 0)

        // 当前用户是否有留言权限
        messageShow.value =
            messageFirst?.cc.some((item: any) => item.username === store.AppState.userName) ||
            messageFirst?.to?.username === store.AppState.userName ||
            messageFirst?.from?.username === store.AppState.userName ||
            userInfo.value?.reporter?.username === store.AppState.userName ||
            userInfo.value?.supervisor?.username === store.AppState.userName

        //确认提交cc
        const resubmit: any = buttonList.value.find((item: any) => item.name === 'resubmit_ticket')?.init_data
            .cc

        //修改提交cc
        const editCc: any = buttonList.value.find((item: any) => item.name === 'commit_ticket')?.init_data
            .cc

        const params = {
            created_by: userInfo.value.create_by?.id, //工单创建人
            created_by_name: userInfo.value.create_by?.name, //工单创建人
            supervisor: userInfo.value.supervisor?.id, //负责人
            supervisor_name: userInfo.value.supervisor?.name, //负责人
            customer: userInfo?.value.customer?.name, // FAB名称
            customer_id: userInfo?.value.customer?.id, // FAB ID
            reporter: userInfo.value.reporter?.id, // 客户联系人
            reporter_name: userInfo.value.reporter?.name, // 客户联系人
            phone_number: userInfo.value.reporter_phone, //电话
            email_address: userInfo.value.reporter_email, //邮箱
            ticket_type: ticketInfo.value.ticket_type, //工单类型id
            ticket_type_name: workTypeIssue[ticketInfo.value.ticket_type], //工单类型名称
            ticket_cate: ticketInfo.value.ticket_cate, //工单分类id
            ticket_cate_name: workClassify[ticketInfo.value.ticket_cate], //工单分类名称
            device_sn_cust: ticketInfo.value.device_sn_cust.id, //客户设备编号id
            device_sn_cust_name: ticketInfo.value.device_sn_cust.name, //客户设备编号name
            device_status: ticketInfo.value.device_status, //设备状态id
            device_status_name: ticketInfo.value.device_status ? '设备无法运行' : '设备可以运行', //设备状态name
            device_type: ticketInfo.value.device_type, //设备型号
            device_sn: ticketInfo.value.device_sn, //设备序列号
            device_warranty: ticketInfo.value.device_warranty, //设备保修日
            component_warranty: ticketInfo.value.component_warranty, //部件保修日
            ticket_title: ticket.value.ticket_title, //标题
            to_user: userInfo.value.supervisor?.id, //TO
            to_user_name: userInfo.value.supervisor?.name, //TO
            // cc_list: res.data.cc_candidates,
            ticket_desc: ticket.value.ticket_desc, //详细描述
            attachment: ticket.value.attachments, //附件
            ticket_number: workNumber.value
        }

        subMitData.value = params

        emit('edit', currentState.value)
        
        // 数据加载完成后立即更新视口高度
        nextTick(() => {
            setViewportHeight();
        });
    } catch (err) {
        // errError(err)
    }
}

//附件下载
const downloadFile = async (name: string, url: string) => {
    try {
        const res: any = await workAttachmentDownload({ file_path: url })

        download(res.download_url, name)

    } catch (err) {
        //
    }
}
</script>

<style lang="scss" scoped>
// .work-detail-content-button {
//     display: flex;
//     align-items: center;

//     .work-detail-dispose {
//         width: 70px;
//         height: 28px;
//         border-radius: 8px;
//     }
// }

.person-name {
    width: 150px;
    line-height: 20px;
    margin-right: 20px;

    .file-upload {
        margin-bottom: 10px;
        color: rgb(3, 73, 231);
        width: 210px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

/* 按钮容器样式 */
.button-container {
    position: fixed;
    bottom: -5px;
    left: 0;
    right: 0;
    z-index:99;
    // background: #fff;
    height: 45px; /* 固定高度 */
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    padding: 0;
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    will-change: transform;
    /* 添加过渡效果，使按钮平滑显示 */
    transition: opacity 0.1s ease;
    opacity: 1;
    visibility: visible;
}

.work-detail-dispose {
    width: 340px;
    height: 35px;
    border-radius: 0;
    margin: 0;
    padding: 0;
    /* 确保按钮文字立即可见 */
    opacity: 1;
    visibility: visible;
}

/* 确保内容不被按钮遮挡 */
:deep(.van-form) {
    padding-bottom: calc(var(--bottom-height, 45px) + 20px); /* 使用组件级别的变量 */
}

:deep(.van-cell-group) {
    margin-bottom: 0;
    position: relative;
    z-index: 1;
}

:deep(.van-cell) {
    margin-bottom: 0;
    position: relative;
    z-index: 1;
}

/* 安卓Edge浏览器特定样式 */
.android-edge {
    :deep(.van-form) {
        padding-bottom: 160px !important; /* 增加底部边距，从120px改为160px */
        overflow-y: auto !important;
        -webkit-overflow-scrolling: touch;
    }
    
    :deep(.van-cell-group) {
        padding-bottom: 160px !important; /* 增加底部边距，从120px改为160px */
    }
    
    :deep(.detail-list) {
        padding-bottom: 160px !important; /* 增加底部边距，从120px改为160px */
        margin-bottom: 160px !important;  /* 增加底部边距，从120px改为160px */
    }
    
    .button-container {
        height: 45px;
    }
}

/* 修复移动设备视口高度问题 */
@media screen and (max-width: 768px) {
    .detail-subassembly-container :deep(.van-form) {
        min-height: calc(var(--vh, 1vh) * 100 - var(--bottom-height, 50px));
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .detail-subassembly-container :deep(.detail-list) {
        margin-bottom: calc(var(--bottom-height, 50px) + 30px); /* 增加底部边距 */
    }
}
</style>